/**
 * Copyright (C) 2013-2014 the original author or authors.
 */
package com.foreveross.bsl.system.application.impl.extend;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.inject.Named;

import org.apache.commons.lang3.StringUtils;
import org.apache.http.Consts;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.foreveross.bsl.common.utils.exception.AppExcType;
import com.foreveross.bsl.common.utils.exception.ApplicationException;
import com.foreveross.bsl.system.application.extend.AuthTypeApplication;
import com.foreveross.bsl.system.application.extend.vo.AuthInfoVO;
import com.foreveross.bsl.system.application.extend.vo.AuthResultVO;
import com.foreveross.bsl.system.application.extend.vo.AuthSettingVO;


/**
 * @description
 *
 * @author rening
 * @version v1.0
 *
 * @2013-9-22
 *
 */
@Named("HttpAuthApplication")
public class HttpAuthApplicationImpl implements AuthTypeApplication {

	private static Logger logger = LoggerFactory.getLogger(HttpAuthApplicationImpl.class);
	
	/* (non-Javadoc)
	 * @see com.foreveross.bsl.system.extend.application.AuthApplication#auth(com.foreveross.bsl.system.extend.application.vo.AuthInfoVO, com.foreveross.bsl.system.extend.application.vo.AuthSettingVO)
	 */
	@Override
	public AuthResultVO auth(AuthInfoVO authInfo, AuthSettingVO authSetting) {
		
		StringBuffer url = new StringBuffer();
		url.append(authSetting.getProtocol()).append("://");
		
		if(StringUtils.isNotEmpty(authSetting.getDomain())){
			url.append(authSetting.getDomain());
		} else {
			url.append(authSetting.getIp());
		}
		
		if(StringUtils.isNotEmpty(authSetting.getPort())){
			url.append(":").append(authSetting.getPort());
		}
		
		if(StringUtils.isNotEmpty(authSetting.getUri())){
			url.append(authSetting.getUri());
		}
		
		HttpClient httpClient = new DefaultHttpClient();

		List<NameValuePair> formparams = new ArrayList<NameValuePair>();
		formparams.add(new BasicNameValuePair("username", authInfo.getUsername()));
		formparams.add(new BasicNameValuePair("password", authInfo.getPassword()));
		if(authInfo.getAppKey() != null){
			formparams.add(new BasicNameValuePair("appKey", authInfo.getAppKey()));
		}
		if(authInfo.getAppId() != null){
			formparams.add(new BasicNameValuePair("appId", authInfo.getAppId()));
		}
		UrlEncodedFormEntity entity = new UrlEncodedFormEntity(formparams, Consts.UTF_8);
		HttpPost httpPost = new HttpPost(url.toString());
		httpPost.setEntity(entity);
		
		HttpResponse response;
		AuthResultVO result = new AuthResultVO();
		try {
			response = httpClient.execute(httpPost);
			int code = response.getStatusLine().getStatusCode();
			HttpEntity httpEntity = response.getEntity();
			String content = EntityUtils.toString(httpEntity);
			logger.info(content);
			if(code == 200){
				result.setResult(true);
				result.setMessage(content);
				Header cookie = response.getFirstHeader("set-cookie");
				if(cookie != null){
					result.setSetCookie(cookie.getValue());
				}
			} else if(code == 303){
				result.setResult(false);
				result.setMessage(content);
			} else {
				logger.error(response.getStatusLine().toString());
				throw new ApplicationException(AppExcType.getBusCode(AppExcType.APP_LAYER, AppExcType.SYS_MODUL, "034"), "external system auth fail ");
			}
		} catch (ClientProtocolException e) {
			logger.error(e.getMessage(),e);
			throw new ApplicationException(AppExcType.getBusCode(AppExcType.APP_LAYER, AppExcType.SYS_MODUL, "032"), "external system protocol exception ");
		} catch (IOException e) {
			logger.error(e.getMessage(),e);
			throw new ApplicationException(AppExcType.getBusCode(AppExcType.APP_LAYER, AppExcType.SYS_MODUL, "033"), "external system connection exception ");
		}
		return result;
	}

	public static void main(String[] args) {
		AuthTypeApplication aa = new HttpAuthApplicationImpl();
		AuthInfoVO ai = new AuthInfoVO();
		ai.setUsername("cube");
		ai.setPassword("sd");
		AuthSettingVO as = new AuthSettingVO();
//		as.setDomain("iproduct.foreveross.com");
		as.setIp("115.28.1.109");
		as.setPort("8080");
		as.setProtocol("http");
		as.setUri("/bsl-web/system/account/login");
		System.out.println(aa.auth(ai, as));
	}
}
